<template>
  <div
    :id="pageData.nodeId"
    class="ProcessNode_container"
    @mouseenter="mouseenterEdit"
    @mouseleave="mouseleaveEdit"
  >

    <div class="ProcessNode_main">

      <div class="ProcessNode_main_name">
        {{ itemData.data.engineeringProcessName }}
        <!--        {{ itemData.data.engineeringProcessName }}：{{ pageData.nodeId }}-->
      </div>

      <div class="ProcessNode_main_bottom">
        <div class="ProcessNode_main_bottom_item">{{ pageData.productBySelf=='1'?'自己生产':'外协' }}</div>
        <div class="ProcessNode_main_bottom_item">{{ pageData.toInspect=='1'?'送检':'不送检' }}</div>
        <div class="ProcessNode_main_bottom_item">{{ pageData.toWms=='1'?'入库':'不入库' }}</div>
      </div>
    </div>
    <div v-if="$store.state.engineeringManage.showDetail" class="ProcessNode_right">
      <el-popover
        placement="right"
        width="300"
        trigger="click"
        :visible-arrow="false"
        popper-class="ProcessNode_popover"
      >
        <div class="ProcessNode_hover">
          <div class="ProcessNode_hover_item">
            <div class="ProcessNode_hover_item_name">
              标记工序
            </div>
            <div class="ProcessNode_hover_item_value">
              <el-radio-group v-model="pageData.productBySelf" @change="updateNodeDatas">
                <el-radio label="1">自己生产</el-radio>
                <el-radio label="0">外协</el-radio>
              </el-radio-group>
            </div>
          </div>
          <div class="ProcessNode_hover_item">
            <div class="ProcessNode_hover_item_name">
              是否送检
            </div>
            <div class="ProcessNode_hover_item_value">
              <el-radio-group v-model="pageData.toInspect" @change="updateNodeDatas">
                <el-radio label="1">送检</el-radio>
                <el-radio label="0">不送检</el-radio>
              </el-radio-group>
            </div>
          </div>
          <div class="ProcessNode_hover_item">
            <div class="ProcessNode_hover_item_name">
              是否入库
            </div>
            <div class="ProcessNode_hover_item_value">
              <el-radio-group v-model="pageData.toWms" @change="updateNodeDatas">
                <el-radio label="1">入库</el-radio>
                <el-radio label="0">不入库</el-radio>
              </el-radio-group>
            </div>
          </div>
          <div class="ProcessNode_hover_item">
            <div class="ProcessNode_hover_item_name">
              标准工时（时）
            </div>
            <div class="ProcessNode_hover_item_value">
              <el-input
                v-model="pageData.standardWorkTime"
                placeholder="请输入"
                @input="updateNodeDatas"
              />
            </div>
          </div>
          <div class="ProcessNode_hover_item">
            <div class="ProcessNode_hover_item_name">
              工时单价（元）
            </div>
            <div class="ProcessNode_hover_item_value">
              <el-input
                v-model="pageData.workTimePrice"
                placeholder="请输入"
                @input="updateNodeDatas"
              />
            </div>

          </div>
          <div class="ProcessNode_hover_item_tips">（计时或计件单价二选一即可，如果均填写，系统将默认以计件单价为准统计工资。）</div>
          <div class="ProcessNode_hover_item">
            <div class="ProcessNode_hover_item_name">
              计件单价（元）
            </div>
            <div class="ProcessNode_hover_item_value">
              <el-input
                v-model="pageData.unitPriceOfPiecework"
                placeholder="请输入"
                @input="updateNodeDatas"
              />
            </div>

          </div>
          <div class="ProcessNode_hover_item_tips">（计时或计件单价二选一即可，如果均填写，系统将默认以计件单价为准统计工资。）</div>
        </div>
        <div v-show="showEdit" slot="reference" class="ProcessNode_main_edit animate__animated animate__fadeInLeft">
          编辑
        </div>

      </el-popover>

      <!--      <div v-show="showEdit" class="ProcessNode_main_edit ProcessNode_main_choose animate__animated animate__fadeInLeft" @click="chooseMaterial">-->
      <!--        &lt;!&ndash;        <svg-icon icon-class="选择弹框" />&ndash;&gt;-->
      <!--        选择物料-->
      <!--      </div>-->

      <div v-if="showEdit" slot="reference" class="ProcessNode_main_edit ProcessNode_main_delete animate__animated animate__fadeInLeft" @click="deleteNode">
        删除
      </div>
    </div>
  </div>
</template>

<script>
import 'animate.css'
import ChooseMaterial from './ChooseMaterial.vue'
import { mapGetters } from 'vuex'
export default {
  name: 'ProcessNode',

  computed: {
    ...mapGetters([
      'graphData', 'processNodeData'
    ])
  },
  props: {
    // 这里可以拿到mockdata里的当前节点的数据
    itemData: {
      type: Object
    }
  },
  data() {
    return {
      hasChoseMaterial: [],
      showEdit: false,
      showEdit2: false,
      showProcessPopover: undefined,
      showPopover: false,
      pageData: {
        id: '',
        nodeId: '',
        engineeringProcessId: '',
        engineeringProcessName: '',
        productBySelf: '',
        toInspect: '',
        toWms: '',
        standardWorkTime: '',
        workTimePrice: '',
        unitPriceOfPiecework: ''
      }
    }
  },
  created() {
    Object.keys(this.pageData).forEach(key => {
      this.pageData[key] = this.itemData.data[key] ? JSON.parse(JSON.stringify(this.itemData.data[key])) : ''
    })
  },
  methods: {
    hasChooseChildrenMaterial() {
      var arr = []
      const nodes = this.$deepClone(this.graphData.nodes)
      const edges = this.$deepClone(this.graphData.edges)
      const ids = edges.filter(item => item.source == this.itemData.id).map(item => item.target)// 获取当前节点下的所有子节点id
      ids.forEach(item => {
        if (nodes.filter(item2 => item2.id == item).length > 0) {
          arr.push(nodes.filter(item2 => item2.id == item)[0])
        }
      })
      return arr.map(item => item.data)
    },
    findParentNode(tree, nodeId, parent = null) {
      if (tree.nodeId === nodeId) {
        return parent // 找到了目标节点，返回其父节点
      }

      for (const child of tree.children) {
        const result = this.findParentNode(child, nodeId, tree.nodeId)
        if (result) {
          return result // 在子节点中找到目标节点，返回结果
        }
      }

      return null // 没有找到目标节点
    },
    flattenTree(tree, targetNodeId) {
      const result = new Set()
      function dfs(node, path) {
        path.push({ materialId: node.materialId, nodeId: node.nodeId })
        if (node.nodeId === targetNodeId) {
          for (const item of path) {
            result.add(JSON.stringify(item))
          }
        }
        for (const child of node.children) {
          dfs(child, [...path])
        }
      }
      dfs(tree, [])
      return Array.from(result).map(item => JSON.parse(item)).map(item => item.materialId).filter(item => item)
    },

    findParentIds(tree, nodeId, result = []) {
      // console.log('tree', tree)
      // for (const node of tree) {
      //   if (node.nodeId === childId) {
      //     return result
      //   }
      //   if (node.children) {
      //     if (node.materialId) {
      //       result.push(node.materialId)
      //     }
      //     const parentIds = this.findParentIds(node.children, childId, result)
      //     if (parentIds.length > 0) {
      //       return parentIds
      //     }
      //     result.pop()
      //   }
      // }
      // return []
    },
    buildTree(nodes, edges) {
      const nodeMap = new Map()
      // 使用节点的 id 创建节点映射
      for (const node of nodes) {
        nodeMap.set(node.id, { ...node.data, children: [] })
      }
      // 构建树结构
      for (const edge of edges) {
        var sourceNode = nodeMap.get(edge.source)
        var targetNode = nodeMap.get(edge.target)
        // 如果找到源节点和目标节点，则将目标节点添加为源节点的子节点
        if (sourceNode && targetNode) {
          sourceNode.children.push(targetNode)
        }
      }
      // 查找根节点
      const rootNodes = nodes.filter((node) => !edges.some((edge) => edge.target === node.id))
      return rootNodes.map((rootNode) => nodeMap.get(rootNode.id))
    },
    mouseenterEdit() {
      this.showEdit = true
      this.showEdit2 = true
    },
    mouseleaveEdit() {
      this.showEdit2 = false
      setTimeout(() => {
        if (!this.showEdit2) {
          this.showEdit = false
        }
      }, 200)
    },
    chooseMaterial() {
      this.showEdit = false
      const nodes = this.$deepClone(this.graphData.nodes)
      const edges = this.$deepClone(this.graphData.edges)
      const nodeTrees = this.buildTree(nodes, edges)
      const childrenIdArr = this.findChildNodes(nodeTrees, this.pageData.nodeId).map(item => item.materialId)
      this.$layer.iframe({
        // 弹框
        content: {
          content: ChooseMaterial, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: [],
            excludeSelect: [...this.flattenTree(...nodeTrees, this.itemData.data.nodeId), ...childrenIdArr]
          } // 当前主物料和当前点击的父级物料不能勾选
        },
        area: ['1320px', '700px'],
        title: '选择物料', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    findChildNodes(tree, nodeId) {
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        if (node.nodeId === nodeId) {
          return node.children || []
        }
        if (node.children) {
          const result = this.findChildNodes(node.children, nodeId)
          if (result.length > 0) {
            return result
          }
        }
      }
      return []
    },

    chooseMaterialCallBack(rows) {
      this.$store.state.engineeringManage.addMaterialData = {
        fromData: this.itemData,
        toData: rows
      }
      console.log(this.$store.state.engineeringManage.updateNodeData)
    },
    updateNodeDatas() {
      this.$store.commit('engineeringManage/CHANGE_SETTING', this.$deepClone(this.pageData))
    },
    deleteNode() {
      this.$store.commit('engineeringManage/CHANGE_DELETE', this.$deepClone(this.pageData))
    }
  }
}
</script>

<style lang="less" scoped>
.ProcessNode_container{
  display: flex;align-items: center;
  position: relative;
}
.ProcessNode_main {
  z-index: 1000;
  width: 174px;
  //height: 36px;

  border-radius: 36px;
  // font-weight: bold;

  //background-color: rgba(142, 176, 240,1);
  background-color: #1DC68E;
  .ProcessNode_main_name{
    //height: 36px;
    width: 100%;
    display: flex;align-items: center;
    font-weight: normal;
    color: white;
    font-size: 14px;
    margin-top: 8px;
    margin-left: 20px;
  }
  .ProcessNode_main_bottom{
    display: flex;align-items: center;
    margin-bottom: 4px;
    margin-top: 1px;
    margin-left: 12px;
    .ProcessNode_main_bottom_item{
      margin-left: 8px;
      // border: 2px solid orange;
      font-size: 12px;
      color: antiquewhite;
      display: flex;align-items: center;
      margin-bottom: 4px;
    }
  }
}
.ProcessNode_right{
  position: absolute;
  left: 180px;
  // z-index: 99999;
}
.ProcessNode_main_edit{
  cursor: pointer;
  width: 60px;height: 25px;border-radius: 5px;
  margin-left: 10px;color: white;

  background-color: #1DC68E;
  font-size: 12px;
  display: flex;align-items: center;justify-content: center;
}
.ProcessNode_main_choose{
  margin-top: 3px;
  background-color: #4FAEFF;
}
.ProcessNode_main_delete{
  background-color: #FF6370;
  margin-top: 5px;
}
</style>
<style lang="less" >
.ProcessNode_popover{
  background-color: #fff;
  border-left: 2px solid rgba(25, 190, 107,1);
  .ProcessNode_hover_item{
    display: flex;align-items: center;
    height: 35px;
    // border-bottom: 1px solid rgba(25, 190, 107,1);
    .ProcessNode_hover_item_name{
      width: 100px;
      font-size: 14px;
      color: #333333;
    }
    .ProcessNode_hover_item_value{
      flex: 1;
      .el-input__inner{
        height: 25px;
        line-height: 1;
      }
    }
  }
  .ProcessNode_hover_item:last-child{
    border: 0;
  }
  .ProcessNode_hover{

    .ProcessNode_hover_header{
      display: flex;align-items: center;justify-content: center;
      height: 35px;font-weight: bold;
      background-color: #eef0f4;color: black;
    }
    .ProcessNode_hover_list{
      overflow-y: auto;
      max-height: 400px;
      .ProcessNode_hover_list_item{
        cursor: pointer;
        display: flex;align-items: center;
        height: 30px;
        border-bottom: 1px solid #eef0f4;
        color: #999999;
        padding: 0 20px;
      }
      .ProcessNode_hover_list_item:last-child{
        border-bottom:0;
      }
      .ProcessNode_hover_list_item:hover{
        color: white;
        background-color: rgba(142, 176, 240,1);
      }
    }
  }
}
.ProcessNode_popover_process{
  padding: 0;
  border: 2px solid rgba(25, 190, 107,1);
}
.ProcessNode_hover_item_tips{
  height: 25px;
  font-size: 12px;
  line-height: 1;
  display: flex;
  align-items: center;
  color: #CCCCCC;
  margin-top: -2px;
}
</style>
